<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam"
      data-key="roleInformationDTOList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <SButton :buttonProps="{ type: 'primary' }" buttonText="新增" contentType="both" icon="CirclePlus"
          @click="openDialog('新增')" />
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <!-- <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="人员列表"
          @click="toListOfPersonnel(scope.row)" /> -->
        <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="编辑" @click="openDialog('编辑', scope.row)" />
        <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="删除" @click="handleDeleteRole(scope.row)" />
      </template>
    </ProTable>


    <RoleDialog ref="roleDialogRef" :title="dialogTitle" :rowData="selectedRow" v-model:visible="dialogVisible"
      @refresh="proTable?.getTableList" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { User } from "@/api/interface";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import ProTable from "@/components/ProTable/index.vue";
import RoleDialog from "./modules/RoleDialog.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import SButton from "@/components/SButton/index.vue";
import { dayjs, ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useDataStore } from '@/stores/modules/data'
import { addRole, deleteRole, editRole, roleListPaginationQuery } from "@/api/basic/role";


const dataStore = useDataStore()

// ProTable 实例
const proTable = ref<ProTableInstance>();
const initParam = reactive({});
const getTableList = (params: any) => {
  return roleListPaginationQuery(params);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

onMounted(async () => {
  await dataStore.fetchRoleList();
});

const roleList = computed(() => dataStore.roleList);

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  {
    prop: "roleName",
    label: "角色",
    search: { el: "input" },
    // search: { el: "select", key: "id" },
    // enum: roleList,
    // isFilterEnum: false,
    // fieldNames: { label: "roleName", value: "id" },
  },
  {
    prop: "createBy",
    label: "创建人",
    search: { el: "input" },
  },
  {
    prop: "createTime", label: "创建时间", search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD" },
    },
    render: scope => {
      return (
        <>
          <span>{dayjs(Number(scope.row.createTime) * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
        </>
      );
    }
  },
  {
    prop: "updateTime", label: "更新时间",
    render: scope => {
      return (
        <>
          <span>{dayjs(Number(scope.row.updateTime) * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
        </>
      );
    }
  },
  { prop: "operation", label: "操作", fixed: "right" }
]);


// 打开 dialog(新增、查看、编辑)
const dialogTitle = ref('');
const dialogVisible = ref(false);
const selectedRow = ref<Partial<User.ResUserList>>({});
const roleDialogRef = ref<InstanceType<typeof RoleDialog> | null>(null);

const openDialog = (title: string, row: Partial<User.ResUserList> = {}) => {
  dialogTitle.value = title;
  selectedRow.value = row;
  dialogVisible.value = true;
  roleDialogRef.value?.acceptParams({
    title,
    isView: title === '详情',
    row,
    api: title === '新增' ? addRole : editRole,
    getTableList: proTable.value?.getTableList
  });
};

//删除角色
const handleDeleteRole = (row: any) => {
  ElMessageBox.confirm("确定删除该角色吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteRole(row.id);
    ElMessage.success("删除角色成功");
    proTable.value?.getTableList();
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
}

//人员列表
// const router = useRouter();
// const toListOfPersonnel = (row: any) => {
//   router.push(`/system/roleManage/rolePersonList?roleId=${row.id}`);
// }


</script>
